<?php

namespace app\service;

use app\model\User;
use GuzzleHttp\Client;
use Tinywan\Jwt\JwtToken;
use app\enum\UserCode;

class UserService extends Base
{
    //登录
    public function toLoginByCode($code, $platform): array
    {

        $userModel = new User();
        //获取微信小程序的openid
        if ($platform) {
            $openid = $this->get_openid($code);
        } else {
            $openid = $code;
        }
        //查询会员信息
        $userInfo = $userModel->where(['openid' => $openid])->find();
        if (empty($userInfo)) {
            //注册
            $param = [
                'openid' => $openid,
                'nickname' => $data['nickname'] ?? '测试用户_' . rand(1000, 10000),
                'avatar' => $data['avatar'] ?? 'https://ylgys.vip.hnhxzkj.com/wenzhouwaixing.jpg',
                'platform' => $platform,
                'status' =>  UserCode::STATUS_NORMAL,
            ];

            $id = $userModel->insertGetId($param);
            if (!$id) {
                return apiError('注册失败');
            }
            //注册成功
            $userInfo = $userModel->where(['id' => $id])->find();

        }
        if ($userInfo['status'] == UserCode::STATUS_DISABLE) {
            return apiError('该账号已停用');
        }

        $extend = [
            'id' => $userInfo['id'],
            'name' => '模版',
            'access_exp' => 8640000,  // 100天
            'refresh_exp' => 8640000,  // 100天
            'client' => JwtToken::TOKEN_CLIENT_MOBILE
        ];
        $generateToken = JwtToken::generateToken($extend);

        if ($generateToken) {
            $data = ['token' => $generateToken['access_token'], 'user_info' => $userInfo];
            return apiSuccess($data);
        }
        return apiError('失败');

    }

    //获取微信小程序的openid
    protected function get_openid($js_code)
    {
        $appid = env('wx.appId', '');
        $secret = env('wx.appSecret', '');
        //改成
        //创建一个有基本URI的客户端
        $client = new Client();
        //发送请求
        $response = $client->request('GET', 'https://api.weixin.qq.com/sns/jscode2session?appid='. $appid . '&secret='. $secret . '&js_code='. $js_code . '&grant_type=authorization_code');
        //获取返回数据
        $data = json_decode($response->getBody(), true);
        if (isset($data['openid'])) {
            return $data['openid'];
        }
        return $response;
    }

}